package com.qf.dao.impl;

import com.qf.dao.EmpDao;
import com.qf.pojo.Emp;
import com.qf.utils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * delete from emp where id = ?
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
public class EmpDaoImpl implements EmpDao {
    @Override
    public List<Emp> selectAll() {
        String sql = "select * from emp";
        QueryRunner qr = new QueryRunner();

        try {
            List<Emp> empList = qr.query(DbUtils.getConnection(), sql, new BeanListHandler<>(Emp.class));
            return empList;
        } catch (SQLException e) {
            e.printStackTrace();
        }


        return null;
    }

    @Override
    public void delete(String id) {
        String sql = "delete from emp where id = ?";

        QueryRunner qr = new QueryRunner();

        try {
            qr.update(DbUtils.getConnection(), sql , id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Emp findById(String id) {

        String sql = "select * from emp where id = ?";
        QueryRunner qr = new QueryRunner();

        try {
            Emp emp = qr.query(DbUtils.getConnection(), sql, new BeanHandler<>(Emp.class), id);
            return emp;
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public void update(Emp emp) {
        String sql = "UPDATE `emp` SET  `NAME`=?, `SALARY`=?, `AGE`=? WHERE (`ID`=?)";

        QueryRunner qr = new QueryRunner();

        try {
            qr.update(DbUtils.getConnection(), sql , emp.getName(), emp.getSalary(), emp.getAge(), emp.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public long getTotalCount() {
        String sql = "select count(1) from emp ";
        QueryRunner qr = new QueryRunner();

        try {
            long count = qr.query(DbUtils.getConnection(), sql, new ScalarHandler<>());
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return 0;
    }

    @Override
    public List<Emp> findPageData(int startIndex, int pageSize) {

        String sql = "select * from emp limit ?,?";
        QueryRunner qr = new QueryRunner();

        try {
            List<Emp> empList = qr.query(DbUtils.getConnection(), sql, new BeanListHandler<>(Emp.class),startIndex, pageSize);
            return empList;
        } catch (SQLException e) {
            e.printStackTrace();
        }


        return null;
    }
}
